/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Simtest;

import java.util.logging.Level;
import java.util.logging.Logger;
import simframe.simulation.*;
/**
 *
 * @author Steve Noble
 */
public class AgentX extends SimObject {

    static int name = 0;

    final AgentY y;
    final int myName;

    // a swarm action
    public static final Swarm.SwarmAction<AgentX> initSwarm = new Swarm.SwarmAction<AgentX>() {
        public void exec(AgentX x) {
            x.methodA(0);
        }
    };

    // a message
     public Action doMethodA(final int val) {
         return new Action() { public void exec() {
             methodA(val);
         }
         };
     }

     // an action
     public Action getSomethingToDo() {
         return new Action() {
             public void exec() {
                 somethingToDo();
             }
         };
     }

     AgentX(AgentY y) {
         this.y = y;
         myName = name++;
     }

    private synchronized void methodA(int val) {

        System.out.print("X" + Integer.toString(myName));
        System.out.print( " " + Time.toString(this.getTime()));
        System.out.print(" received " + Integer.toString(val));

        if (val < 2) {

            System.out.print(  " sending " + Integer.toString(val + 2) + " --> Y" + Integer.toString(y.myName) + "\n");
            y.action(y.doMethodB(this, val+ 2));
        }
        else {
             System.out.print("   resetting value & Performing actionX\n");
             val = 0;
             action(this.getSomethingToDo(), Time.Hour);
        }
         try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            Logger.getLogger(AgentX.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void somethingToDo() {
         
         System.out.print("X" + Integer.toString(myName));
         System.out.print( " " + Time.toString(this.getTime()));
          System.out.print(" ActionX & sleeping\n");
          try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    Logger.getLogger(AgentX.class.getName()).log(Level.SEVERE, null, ex);
                }

           System.out.print("X" + Integer.toString(myName));
         System.out.print( " " + Time.toString(this.getTime()));
          System.out.print(" ActionX & waking up\n");
    }

    @Override
    public boolean dead() {
       return false;
    }

    @Override
    public void reset() {
//             action( new Action() {
//             public void exec() {
//                methodA(0);
//             }
//
//             @Override
//             public Long nextTime(Long t) {
//                 return Time.next(t, Time.Period.Daily);
//             }
//         }, 18 * Time.Hour );
    }

}
